package com.cabbagetofu.crowd.controller;


import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.until.ResultEntity;
import com.cabbagetofu.crowd.entity.po.MemberPO;
import com.cabbagetofu.crowd.service.api.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class MemberProviderController {

    @Autowired
    private MemberService memberService;

    /**
     * 根据consumer传输过来的数据，将用户的注册信息保存至数据库中
     * @param memberPO
     * @return
     */
    @RequestMapping("/save/member/remote")
    public ResultEntity<String> saveMember(@RequestBody MemberPO memberPO){

        try {
            // 成功保存入数据库中，则直接返回成功结果
            memberService.saveMember(memberPO);
            return ResultEntity.successWithoutData();

        } catch (Exception e) {

            // 如果报DuplicateKeyException异常，则表示注册的账号不唯一，返回失败信息
            if (e instanceof DuplicateKeyException){

                return ResultEntity.failed(CrowdConstant.MESSAGE_LOGIN_ALREADY_IN_USE);
            }

            return ResultEntity.failed(e.getMessage());

        }

    }


    /**
     * 根据账号获取用户信息
     * @param loginacct
     * @return
     */
    @RequestMapping("/get/memberpo/by/login/acct/remote")
    public ResultEntity<MemberPO> getMemberPOByLoginAcctRemote(@RequestParam("loginacct")String loginacct){

        MemberPO memberPO = null;
        try {
            memberPO = memberService.getMemberPOByLoginAcct(loginacct);

            return ResultEntity.successWithData(memberPO);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }



    }

}
